import {
  ConfigEnv,
  loadEnv,
  UserConfigExport
} from 'vite';

// 导入resolve方法
import { resolve } from 'path';

// vite vue插件
import Vue from '@vitejs/plugin-vue';
// VueJsx 解析Jsx的插件
import VueJsx from '@vitejs/plugin-vue-jsx';
// 导入Element-Plus插件
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// svg插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// mock插件
import { viteMockServe } from 'vite-plugin-mock';
import { wrapperEnv } from './src/utils/vite/viteUtil';
// import { wrapperEnv } from '@/utils/vite/viteUtil';
// vue3.3支持defineOption 方式 声明组件名称
// import vueSetupExtend from 'vite-plugin-vue-setup-extend'
// vueSetupExtend(),

// import pkg from './package.json';
// import { wrapperEnv } from "@/utils/viteUtil";


// const resolve = (dir:string)=>path.resolve(__dirname,'.',dir)

// https://vitejs.dev/config/

function pathResolve(dir: string) {
  // return resolve(process.cwd(), '.', dir);
  return resolve(process.cwd(), dir);
}

export default ({ command, mode }: ConfigEnv): UserConfigExport => {

  const root = process.cwd();
  const env = loadEnv(mode, root);
  const isProduction = command === 'build'; 
  const viteEnv = wrapperEnv(env);

  const { VITE_PORT} = viteEnv;
  const sassOptions = {  
    outputStyle: isProduction ? 'compressed' : env.VITE_SASS_OUTPUT_STYLE || 'expanded',  
    sourceMap: isProduction ? false : env.VITE_SASS_SOURCE_MAP !== 'false',  
  }; 
  const additionalData = [`@import "./src/design/index.scss";`]
  
  // console.log('2 :>> ', import.meta.env.VITE_PORT);

  // mode you check
  // console.log('pkg:' + pkg);
  // console.log('mode:>>' + mode);
  // console.log('ROOT:' + root);
  // console.log('process.cwd() :>> ', process.cwd());
  // console.log('dirname :>> ', __dirname);
  // console.log('pathResolve1 :>> ', (pathResolve("src/assets/svg-icons")));
  // console.log('pathResolve1 :>> ' +  resolve(__dirname, "./src"));
  // console.log('222 :>> ' +  pathResolve('src'));
  
  
  // console.log('pathResolve2 :>> ', (resolve(process.cwd(),"src/assets/svg-icons")));
  // console.log('env:' + JSON.stringify(env));
  // console.warn(__dirname);
  // console.warn(pathResolve('') + './src');
  // console.warn(resolve(__dirname,'src' + '/'));
  // console.warn(resolve(process.cwd(), '.', 'src'));

  // console.log('env2:' + import.meta.env.MODE );

  // let base: string = mode === 'development' ? '/dev' : '/'

  return {
    root: process.cwd(),
    base: '/',
    // publicDir?: string | false;
    // cacheDir?: string;
    // mode?: string;
    // define: {
    //   __APP_ENV__: JSON.stringify(env),
    // },
    plugins: [
      Vue(),
      VueJsx(),
      AutoImport({
        imports:[
          'vue',
        ],
        resolvers: [ElementPlusResolver()],
        eslintrc:{},
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/svg-icons')],
        symbolId: 'icon-[dir]-[name]'
      }),
      viteMockServe({
        // mock的文件夹
        mockPath: 'mock',
        // 是否开启mock功能
        localEnabled: command === 'serve',
        prodEnabled:command !== 'serve',
      })
    ],
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathResolve('src'),
        },
      ],
      // extensions:['.js','.ts','.jsx','.tsx','.json']
    },
  
   
    //json?: JsonOptions;
    //esbuild?: ESBuildOptions | false;
    //assetsInclude?: string | RegExp | (string | RegExp)[];
    server:{
      port:VITE_PORT,
      // proxy:{
      //   '/api':{
      //     target:'http://127.0.0.1:8080',
      //     changeOrigin:true,
      //     pathRewrite:{
      //     }
      // }
      // }
    },
    //build?: BuildOptions;
    //preview?: PreviewOptions;
    optimizeDeps: { exclude: ["fsevents"] },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          modifyVars: {
            'primary-color': '#ff0000',// 例如，将主题颜色设置为红色   // 当 LESS 文件编译时，@primary-color 将会被替换为 #ff0000
          },
        },
        scss: {
          javascriptEnabled: true, 
          additionalData,
          sassOptions
        },
      },
    },

    // ssr?: SSROptions;
    //experimental?: ExperimentalOptions;
    //legacy?: LegacyOptions;
    // logLevel?: LogLevel;
    // customLogger?: Logger;
    //clearScreen?: boolean;
    //envDir?: string;
    //envPrefix?: string | string[];
    //worker?: {
    //format?: 'es' | 'iife';
    //plugins?: () => PluginOption[];
    //rollupOptions?: Omit<RollupOptions, 'plugins' | 'input' | 'onwarn' | 'preserveEntrySignatures'>;
  }



}